import React, { useEffect, useRef, useState } from 'react';
import Slider from 'react-slick';
import WorksC from '@/pages/pc/components/Works';
import CourseC from '@/pages/pc/components/Course';
import PackageC from '@/pages/pc/components/Package';
import { Helmet, history } from 'umi';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import styles from './Index.less';
import classNames from 'classnames';
import { allGet } from '@/services/pc';
import { Skeleton } from 'antd';

// 学生作业
const Works = (props) => {
  const [data, setData] = useState(props.data);
  const handleRefresh = async () => {
    const totalPage = Math.floor((data?.data?.count || 15) / 15);
    const randomPage = Math.floor(Math.random() * totalPage) + 1;
    const response = await allGet({
      params: { mod: 'busywork', do: 'list', perpage: '15', page: randomPage, version: 'pc1.0' },
    });
    setData(response);
  };
  return (
    <section className={styles.section}>
      <div className={styles.header}>
        <h3 className={styles.title}>
          {/* <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/xyzy_icon.png')} alt="" /> */}
          学员作品
        </h3>
        <div className={styles.shuaxin} onClick={handleRefresh}>
          <img
            loading="lazy"
            className={styles.icon}
            src={require('@/assets/pc/images/shuaxin.png')}
            alt=""
          />
          换一换
        </div>
      </div>
      <div className={styles.body}>
        {data?.data?.list.length > 0 && <WorksC data={data?.data?.list} itemKey="bid" />}
      </div>
    </section>
  );
};

// 热销课程
const HotClasses = ({ data }) => {
  return (
    <section className={styles.section}>
      <div className={styles.header}>
        <h3 className={styles.title}>
          {/* <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/rxkc_icon.png')} alt="" />  */}
          热销课程
        </h3>
      </div>
      <div className={styles.body}>
        {data?.data?.list.length > 0 && <CourseC open itemKey="classid" data={data?.data?.list} />}
      </div>
    </section>
  );
};

// 最新课程
const NewClasses = ({ data }) => {
  return (
    <section className={styles.section}>
      <div className={styles.header}>
        <h3 className={styles.title}>
          {/* <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/zxkc_icon.png')} alt="" />  */}
          最新课程
        </h3>
      </div>
      <div className={styles.body}>
        {data?.data?.list.length > 0 && <CourseC open itemKey="classid" data={data?.data?.list} />}
      </div>
    </section>
  );
};

// 套餐搭配
const Package = ({ data }) => {
  return (
    <section className={styles.section}>
      <div className={styles.header}>
        <h3 className={styles.title}>
          {/* <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/tcdp_icon.png')} alt="" /> */}
          套餐搭配
        </h3>
      </div>
      <div className={styles.body}>
        {data?.data?.list.length > 0 && <PackageC data={data?.data?.list} itemKey="sid" />}
      </div>
    </section>
  );
};

function NextArrow(props) {
  const { onClick } = props;
  return <i className={styles.nextarrow} onClick={onClick} />;
}

function PrevArrow(props) {
  const { onClick } = props;
  return <i className={styles.prearrow} onClick={onClick} />;
}

const Column = ({ data = {} as any }) => {
  const settings = {
    dots: false,
    infinite: false,
    speed: 500,
    slidesToShow: 7,
    slidesToScroll: 7,
    initialSlide: 0,
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
    responsive: [
      {
        breakpoint: 2100,
        settings: {
          slidesToShow: 6,
          slidesToScroll: 6,
          initialSlide: 2,
        },
      },
      {
        breakpoint: 1660,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 4,
          initialSlide: 2,
        },
      },
      {
        breakpoint: 1446,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 4,
        },
      },
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 4,
        },
      },
    ],
  };

  return (
    <div className={styles.column}>
      <Slider {...settings}>
        {data?.data?.map((item) => {
          return (
            <div key={item.cid}>
              <div className={styles.item}>
                <div className={styles.ratio}>
                  <img
                    src={item.icon}
                    onClick={() => {
                      history.push(`/courses/1?order=-9999&sid=-9999&cid=${item.cid}`);
                      // window.location.href = `/courses/1?order=classid&cid=${item.cid}`
                    }}
                  />
                </div>
              </div>
            </div>
          );
        })}

        {/* <div>
          <div className={styles.item}>
            <div className={styles.ratio}>
              <img loading="lazy" src={require('@/assets/pc/images/index/c2.png')} />
            </div>
          </div>
        </div>
        <div>
          <div className={styles.item}>
            <div className={styles.ratio}>
              <img loading="lazy" src={require('@/assets/pc/images/index/c3.png')} />
            </div>
          </div>
        </div>
        <div>
          <div className={styles.item}>
            <div className={styles.ratio}>
              <img loading="lazy" src={require('@/assets/pc/images/index/c4.png')} />
            </div>
          </div>
        </div>
        <div>
          <div className={styles.item}>
            <div className={styles.ratio}>
              <img loading="lazy" src={require('@/assets/pc/images/index/c5.png')} />
            </div>
          </div>
        </div>
        <div>
          <div className={styles.item}>
            <div className={styles.ratio}>
              <img loading="lazy" src={require('@/assets/pc/images/index/c6.png')} />
            </div>
          </div>
        </div> */}
      </Slider>
    </div>
  );
};

function Banner2NextArrow(props) {
  const { onClick } = props;
  return <i className={styles.nextarrow} onClick={onClick} />;
}

function Banner2PrevArrow(props) {
  const { onClick } = props;
  return <i className={styles.prearrow} onClick={onClick} />;
}
const Banner2 = ({ data = {} as any }) => {
  const settings = {
    // centerMode: true,
    speed: 500,
    autoplay: true,
    nextArrow: <Banner2NextArrow />,
    prevArrow: <Banner2PrevArrow />,
    className: 'slider variable-width',
    dots: false,
    infinite: true,
    centerMode: true,
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
  };
  // const settings = {
  //   dots: false,
  //   infinite: false,
  //   speed: 500,
  //   slidesToShow: 7,
  //   slidesToScroll: 7,
  //   initialSlide: 0,
  //   nextArrow: <NextArrow />,
  //   prevArrow: <PrevArrow />,
  //   // responsive: [
  //   //   {
  //   //     breakpoint: 2100,
  //   //     settings: {
  //   //       slidesToShow: 6,
  //   //       slidesToScroll: 6,
  //   //       initialSlide: 2,
  //   //     },
  //   //   },
  //   //   {
  //   //     breakpoint: 1660,
  //   //     settings: {
  //   //       slidesToShow: 4,
  //   //       slidesToScroll: 4,
  //   //       initialSlide: 2,
  //   //     },
  //   //   },
  //   //   {
  //   //     breakpoint: 1446,
  //   //     settings: {
  //   //       slidesToShow: 4,
  //   //       slidesToScroll: 4,
  //   //     },
  //   //   },
  //   //   {
  //   //     breakpoint: 1024,
  //   //     settings: {
  //   //       slidesToShow: 4,
  //   //       slidesToScroll: 4,
  //   //     },
  //   //   },
  //   // ],
  // };
  return (
    <div className={styles.banner2}>
      <Slider {...settings}>
        {data?.data?.map((item) => (
          <div className={styles.item} key={item.pic} style={{ width: 584 }}>
            <div className={styles.content}>
              {item.link ? (
                <a href={item.link} target="_blank" rel="noreferrer">
                  <img src={item.pic} alt="" />
                </a>
              ) : (
                <img src={item.pic} alt="" />
              )}
            </div>
          </div>
        ))}
      </Slider>
    </div>
  );
};
const Banner = ({ data }) => {
  const timer = useRef<any>();

  const [bannerIndex, setBannerIndex] = useState(0);
  const indexRef = useRef(0);
  const autoSliderTo = () => {
    const index = indexRef.current;
    const total = data?.data?.length;
    const newIndex = index + 1 >= total ? 0 : index + 1;
    indexRef.current = newIndex;
    setBannerIndex(newIndex);
  };

  const interval = () => {
    timer.current = setInterval(autoSliderTo, 3000);
  };
  useEffect(() => {
    interval();
    return () => {
      clearInterval(timer.current);
    };
  }, []);
  const handleHover = (index) => {
    //clearTimeout(stimer.current);
    clearInterval(timer.current);
    setBannerIndex(index);
    indexRef.current = index;
    // stimer.current = setTimeout(() => {
    //   interval();
    // }, 500);
  };
  const handleMouseLeave = () => {
    interval();
  };

  return (
    <>
      {data?.data?.length > 0 && (
        <div className={styles.banner}>
          {data?.data?.map((item, index) =>
            item.link ? (
              <a
                href={item.link}
                key={item.pic}
                className={classNames(styles.banneritem, {
                  [styles.actived]: bannerIndex === index,
                })}
              >
                <img
                  loading="lazy"
                  className={styles.img}
                  src={item.pic}
                  loading="lazy"
                  alt={item.title}
                />
              </a>
            ) : (
              <div
                key={item.pic}
                className={classNames(styles.banneritem, {
                  [styles.actived]: bannerIndex === index,
                })}
              >
                <img
                  loading="lazy"
                  className={styles.img}
                  src={item.pic}
                  loading="lazy"
                  alt={item.title}
                />
              </div>
            ),
          )}
          <i className={styles.bannermask} />
          <div className={styles.bannerinfo} onMouseLeave={handleMouseLeave}>
            {data?.data?.map((item, index) => (
              <div
                key={item.pic}
                onMouseEnter={() => handleHover(index)}
                onClick={() => (window.location.href = item.link)}
                className={classNames(styles.item, { [styles.actived]: bannerIndex === index })}
              >
                {item.title && <div className={styles.title}>{item.title}</div>}
                {item.desc && <div className={styles.des}>{item.desc}</div>}
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
};

const Index = (props): React.ReactNode => {
  return (
    <>
      <Helmet>
        {/* <meta name="keywords" content='111' />
        <meta name="description" content='222' /> */}
      </Helmet>
      <div className="page">
        {props.initialPropsOk ? (
          <>
            <div className={styles.sections}>
              <Banner2 data={props?.slide} />
              <Column data={props?.column} />
              <HotClasses data={props?.course} />
              <NewClasses data={props?.newCourse} />
              <Package data={props.packageData} />
              {/* <Works data={props?.works} /> */}
            </div>{' '}
          </>
        ) : (
          <div>
            <div style={{ width: '100%', height: 343 }}>
              <Skeleton active />
            </div>
            <div
              style={{
                display: 'grid',
                width: '100%',
                gridTemplateColumns: '1fr 1fr 1fr 1fr',
                gap: 20,
              }}
            >
              {new Array(20).fill(1).map((num, index) => (
                <Skeleton key={index + num} active />
              ))}
            </div>
          </div>
        )}
        {props?.test?.toString()}
      </div>
    </>
  );
};

export default Index;

Index.getInitialProps = async ({ match }) => {
  const { path, params } = match;
  const { page } = params;
  const response = [];
  const [slide, column, course, newCourse, packageData] = await Promise.all([
    allGet({ params: { mod: 'index', do: 'slide', version: 'pc1.0' } }),
    allGet({ params: { mod: 'course', do: 'category', version: 'pc1.0' } }),
    // allGet({ params: { mod: 'busywork', do: 'list', perpage: '18', page: 1, version: 'pc1.0' } }),
    allGet({ params: { mod: 'course', do: 'lastsale', perpage: '6', page: 1, version: 'pc1.0' } }),
    allGet({
      params: {
        mod: 'course',
        do: 'list',
        oride: 'classid',
        perpage: '6',
        page: 1,
        version: 'pc1.0',
      },
    }),
    allGet({ params: { mod: 'salesmix', do: 'list', perpage: '6', page: 1, version: 'pc1.0' } }),
  ]);

  return {
    path,
    initialPropsOk: true,
    currentPage: page,
    preFetchData: response,
    slide,
    column,
    course,
    newCourse,
    packageData,
  };
};
